package com.yfunc.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.yfunc.common.persistence.Session;
import com.yfunc.common.persistence.SessionFactory;
import com.yfunc.common.persistence.datasource.DruidDataSourceFactory;
import com.yfunc.common.persistence.defaults.DefaultSessionFactory;
import com.yfunc.common.persistence.defaults.Settings;


@Configuration
@PropertySource({ "classpath:jdbc.properties" })
public class PersistenceConfig {
	
	@Autowired
	private Environment env;

	@Bean
	public DataSource dataSource() {
		DruidDataSourceFactory dataSourceFactory = new DruidDataSourceFactory();
		Properties properties = new Properties();
		properties.put("driverClassName", env.getProperty("jdbc.driver"));
		properties.put("username", env.getProperty("jdbc.user"));
		properties.put("password", env.getProperty("jdbc.pass"));
		properties.put("url", env.getProperty("jdbc.url"));
		dataSourceFactory.setProperties(properties);
		return dataSourceFactory.getDataSource();
	}

	@Bean
	public SessionFactory sessionFactory(DataSource dataSource) {
		Settings settings = new Settings();
		settings.dataSource(dataSource);
		settings.transactionFactory(new ManagedTransactionFactory());
		settings.addMapperDirectory("mapper");
		return new DefaultSessionFactory(settings);
	}

	@Bean
	public Session session(SessionFactory sessionFactory) {
		return sessionFactory.createSession();
	}

}
